package com.wxyzz.satserver.likeenshrine.service.impl;

import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wxyzz.common.core.common.PageParam;
import com.wxyzz.common.core.entity.LikeEnshrine;
import com.wxyzz.common.core.exception.CustmerException;
import com.wxyzz.common.core.utils.DateUtils;
import com.wxyzz.common.core.utils.TokenUtils;
import com.wxyzz.common.redis.utils.RedisUtils;
import com.wxyzz.satserver.likeenshrine.dao.LikeEnshrineDao;
import com.wxyzz.satserver.likeenshrine.param.LikeEnshrineParam;
import com.wxyzz.satserver.likeenshrine.service.LikeEnshrineService;
import com.wxyzz.satserver.likeenshrine.vo.LikeEnshrineVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LikeEnshrineServiceImpl implements LikeEnshrineService {

    @Resource
    private LikeEnshrineDao likeEnshrineDao;

    /**
     * 收藏业务
     * 收藏和取消收藏
     * @param param
     */
    @Override
    public void saveEnshrineInfo(LikeEnshrineParam param) {

        // 获取用户id
        Integer uid = TokenUtils.getUidFromToken();
        // 设置redis 中的key  enshrine:articleId:publishId
        // hash 的 key 为 用户id
        String key = String.format("enshrine:%s:%s", param.getArticleId(),param.getPublishId());

        // 获取 value 值
        Integer v = (Integer) RedisUtils.hashGet(key, uid.toString());

        // 当天文章收藏数 key
        String todayLikeNum = String.format("enshrineNum:%s", DateUtils.formatDate(new Date(), "yyyyMMdd"));


        // 判断 value 值
        if (v == null || v == 0) { // 收藏
            RedisUtils.hashPut(key, uid.toString(), 1);

            if (v != null) {
                // 更新数据库 收藏标记
                int i = likeEnshrineDao.update(null, new LambdaUpdateWrapper<LikeEnshrine>()
                        .set(LikeEnshrine::getStatus, 1)
                        .eq(LikeEnshrine::getUserId, uid)
                        .eq(LikeEnshrine::getArticleId, param.getArticleId()));
                if ( i == 0) {
                    throw new CustmerException(500, "收藏失败");
                }
            } else {
                // 添加 数据库一条收藏记录
                LikeEnshrine likeEnshrine = new LikeEnshrine();
                likeEnshrine.setUserId(uid);
                likeEnshrine.setArticleId(param.getArticleId());
                likeEnshrine.setPublishId(param.getPublishId());
                likeEnshrine.setStatus(1);
                likeEnshrine.setType(2);

                int i = likeEnshrineDao.insert(likeEnshrine);

                if (i == 0) {
                    throw new CustmerException(500, "收藏失败");
                }
            }

            // 收藏数 +1
            RedisUtils.hashIncr(todayLikeNum, param.getArticleId().toString(), 1);
        } else { // 取消收藏
            RedisUtils.hashPut(key, uid.toString(), 0);

            // 修改数据库中的值
            int i = likeEnshrineDao.update(null, new LambdaUpdateWrapper<LikeEnshrine>()
                    .set(LikeEnshrine::getStatus, 0)
                    .eq(LikeEnshrine::getUserId, uid)
                    .eq(LikeEnshrine::getArticleId, param.getArticleId()));
            if (i == 0) {
                throw new CustmerException(500, "取消收藏失败");
            }

            // redis 中点收藏 -1
            RedisUtils.hashIncr(todayLikeNum, param.getArticleId().toString(), -1);

        }
    }

    /**
     * 点赞业务
     * 点赞和取消点赞
     * @param param
     */
    @Override
    public void saveLikeInfo(LikeEnshrineParam param) {
        // 获取用户id
        Integer uid = TokenUtils.getUidFromToken();
        // 设置redis 中的key  like:articleId:publishId
        // hash 的 key 为 用户id
        String key = String.format("like:%s:%s", param.getArticleId(), param.getPublishId());

        // 获取 value 值
        Integer v = (Integer) RedisUtils.hashGet(key, uid.toString());

        // 当天文章点赞数 key
        String todayLikeNum = String.format("likeNum:%s", DateUtils.formatDate(new Date(), "yyyyMMdd"));


        // 判断 value 值
        if (v == null || v == 0) { // 点赞
            RedisUtils.hashPut(key, uid.toString(), 1);

            if (v != null) {
                // 更新数据库 点赞标记
                int i = likeEnshrineDao.update(null, new LambdaUpdateWrapper<LikeEnshrine>()
                        .set(LikeEnshrine::getStatus, 1)
                        .eq(LikeEnshrine::getUserId, uid)
                        .eq(LikeEnshrine::getArticleId, param.getArticleId()));
                if ( i == 0) {
                    throw new CustmerException(500, "点赞失败");
                }
            } else {
                // 添加 数据库一条点赞记录
                LikeEnshrine likeEnshrine = new LikeEnshrine();
                likeEnshrine.setUserId(uid);
                likeEnshrine.setArticleId(param.getArticleId());
                likeEnshrine.setPublishId(param.getPublishId());
                likeEnshrine.setStatus(1);
                likeEnshrine.setType(1);
                int i = likeEnshrineDao.insert(likeEnshrine);
                if (i == 0) {
                    throw new CustmerException(500, "点赞失败");
                }
            }

            // 点赞数 +1
            RedisUtils.hashIncr(todayLikeNum, param.getArticleId().toString(), 1);
        } else { // 取消点赞
            RedisUtils.hashPut(key, uid.toString(), 0);

            // 修改数据库中的值
            int i = likeEnshrineDao.update(null, new LambdaUpdateWrapper<LikeEnshrine>()
                    .set(LikeEnshrine::getStatus, 0)
                    .eq(LikeEnshrine::getUserId, uid)
                    .eq(LikeEnshrine::getArticleId, param.getArticleId()));
            if (i == 0) {
                throw new CustmerException(500, "取消点赞失败");
            }

            // redis 中点赞数 -1
            RedisUtils.hashIncr(todayLikeNum, param.getArticleId().toString(), -1);

        }
    }

    /**
     * 获取用户对某篇文章的点赞记录信息
     * @param articleId
     * @return
     */
    @Override
    public LikeEnshrine getLikeInfo(Integer articleId) {
        Integer uid = TokenUtils.getUidFromToken();
        LikeEnshrine likeEnshrine = likeEnshrineDao.selectOne(new LambdaQueryWrapper<LikeEnshrine>()
                .eq(LikeEnshrine::getUserId, uid)
                .eq(LikeEnshrine::getArticleId, articleId)
                .eq(LikeEnshrine::getType, 1));

        return likeEnshrine;
    }

    /**
     * 获取用户对某篇文章的收藏记录信息
     * @param articleId
     * @return
     */
    @Override
    public LikeEnshrine getEnshrineInfo(Integer articleId) {
        Integer uid = TokenUtils.getUidFromToken();
        LikeEnshrine likeEnshrine = likeEnshrineDao.selectOne(new LambdaQueryWrapper<LikeEnshrine>()
                .eq(LikeEnshrine::getUserId, uid)
                .eq(LikeEnshrine::getArticleId, articleId)
                .eq(LikeEnshrine::getType, 2));

        return likeEnshrine;
    }

    /**
     *  哪些用户点赞或收藏了我发表的文章
     *
     * @return
     */
    @Override
    public Page<LikeEnshrineVO> getLikeAndEnshrineInfo(PageParam param) {
        // 获取用户id
        Integer uid = TokenUtils.getUidFromToken();
        Page<LikeEnshrineVO> page = new Page<>(param.getPage(), param.getPageSize());
        // 获取点赞收藏信息
        page = likeEnshrineDao.selectLikeAndEnshrineInfo(page, uid);

        // 通过stream流 获取文章图片的第一张图片
        List<LikeEnshrineVO> records = page.getRecords();
        List<LikeEnshrineVO> list = records.stream().map(item -> {
            String imgPath = item.getImgPath();
            if (StringUtils.hasLength(imgPath)) {
                item.setImgPath(imgPath.split(",")[0]);
            }
            return item;
        }).collect(Collectors.toList());

        Page<LikeEnshrineVO> likeEnshrineVOPage = page.setRecords(list);

        return likeEnshrineVOPage;
    }

    /**
     *  获取我的 所有文章的点赞和收藏数
     * @return int
     */
    @Override
    public int getLikeAndEnshrineCount() {

        Integer uid = TokenUtils.getUidFromToken();

        Long l = likeEnshrineDao.selectCount(new LambdaQueryWrapper<LikeEnshrine>()
                .eq(LikeEnshrine::getPublishId, uid)
                .eq(LikeEnshrine::getStatus, 1));
        Integer i = Integer.valueOf(l.toString());

        return i;
    }

    // 当前用户是否点赞过该文章
    @Override
    public int isLike(Integer uid, Integer aid, Integer type) {
        LikeEnshrine likeEnshrine = likeEnshrineDao.selectOne(new LambdaQueryWrapper<LikeEnshrine>()
                .eq(LikeEnshrine::getUserId, uid)
                .eq(LikeEnshrine::getArticleId, aid)
                .eq(LikeEnshrine::getType, type));
        if (likeEnshrine != null) {
            return likeEnshrine.getStatus();
        }
        return 0;
    }

    // 当前用户是否收藏过该文章
    @Override
    public int isCollect(Integer uid, Integer aid, Integer type) {
        LikeEnshrine likeEnshrine = likeEnshrineDao.selectOne(new LambdaQueryWrapper<LikeEnshrine>()
                .eq(LikeEnshrine::getUserId, uid)
                .eq(LikeEnshrine::getArticleId, aid)
                .eq(LikeEnshrine::getType, type));
        if (likeEnshrine != null) {
            return likeEnshrine.getStatus();
        }
        return 0;
    }


}

